package com.sts.transform.impl;

import cn.hutool.core.util.StrUtil;
import com.googlecode.aviator.AviatorEvaluator;
import com.sts.transform.StsTransform;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author lsl
 * @since 2025年07月08日 19:41
 */
public class RuleProcessTransformImpl implements StsTransform<List<String>> {

    private final List<String> ruleList;

    public RuleProcessTransformImpl(List<String> ruleList) {
        this.ruleList = ruleList;
    }

    @Override
    public Stream<List<String>> transform(Stream<List<String>> dataStream) {
        return dataStream.map(this);
    }

    @Override
    public List<String> apply(List<String> row) {
        int minSize = Math.min(row.size(), ruleList.size());

        List<String> resultList = new ArrayList<>(minSize);
        for (int i = 0; i < minSize; i++) {
            String value = row.get(i);
            String rule = ruleList.get(i);
            if (StrUtil.isNotBlank(rule)) {
                Object executeValue = AviatorEvaluator.execute(rule, Map.of("cell", value), true);
                if (executeValue != null) {
                    value = String.valueOf(executeValue);
                } else {
                    value = null;
                }
            }

            resultList.add(value);
        }
        return resultList;
    }
}
